import React from 'react'
import Progress from './progress.jsx'
import AsyncButton from './async-button.jsx'
import Pagination from './Pagination.jsx'
import F from 'lodash/fp'
import {connect} from 'react-redux'
import {fileQueued, fileProgress, fileStatusChange, selectPhoto, selectedPhoto, deletedPhote, switchPage, cropperReady} from '../actions/content-change'

const PhotoList = props => {
    return (
        <ul>
            {props.photos.map(t => {
                return (
                    <li className={t.id == props.selectedId ? "copper-img layer-item-select" : "copper-img"} key={t.id} onClick={() => props.selectPhoto(t)}>
                        <img src={t.thumb} />
                        <AsyncButton to={`/user-gallery/delete/${t.id}`} onResolve={() => props.deletePhoto(t.id)} />
                        {
                            t.status === 'uploading' 
                            ? <Progress percentage={t.percentage ? t.percentage : 0} />
                            : t.status === 'error' 
                            ? <p>上传失败</p> 
                            : t.status === 'success'
                            ? <p>上传成功</p>
                            : ''
                        }
                    </li>
                )
            })}
        </ul>
    )
}

class UserGallery extends React.Component {
    componentDidMount() {
        let {fileQueued, fileProgress, fileStatusChange} = this.props

        if (!window.uploader) {
            window.uploader = WebUploader.create({
                // 文件接收服务端。
                server: this.props.uploadServer,

                pick: '#picker',

                // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                resize: false,
                auto: true,
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,bmp,png',
                    mimeTypes: 'image/jpg,image/png,image/gif,image/jpeg,image/bmp'
                }
            });


            uploader.on('fileQueued', file => {
                uploader.makeThumb(file, function(error, src) {
                    if (error) return alert(error)
                    fileQueued({
                        id: file.id,
                        thumb: src,
                        status: 'uploading'
                    })
                }, 115, 65)
            })

            // 文件上传过程中创建进度条实时显示。
            uploader.on('uploadProgress', fileProgress)

            uploader.on('uploadError', file => fileStatusChange(file, 'error'))

            uploader.on('uploadSuccess', (file, res) => fileStatusChange(file, 'success', res))

        }
    }

    render () {
        let {photos, photoSelected, selectPhoto, deletePhoto, switchPage, pagedPhotos, curPage, selectedId} = this.props
        return (
            <div className="am-modal-bd change-cover-bd">
                <div className="change-cover-bd-l">
                    <div className="my-album">我的图库</div>
                    <div className="am-form-group am-form-file">
                        <button 
                            className="am-btn am-btn-default am-btn-sm upload-btn" 
                            id="picker"
                            onClick={() => document.querySelector('#picker .webuploader-element-invisible').click()}
                        >
                            <i className="am-icon-cloud-upload"></i> <span>上传</span>
                        </button>
                    </div>
                    <p className="upload-tips">
                        大小不超过10M <br/> 
                        支持格式：JPG、png、gif<br/>
                        <a href="/article/changjianwenti/6969.html" target="_blank">点此下载图片压缩工具</a>
                    </p>
                </div>
                <div className="change-cover-bd-r">
                    <div className="change-cover-bd-r-top">
                        <PhotoList photos={pagedPhotos} selectPhoto={selectPhoto} deletePhoto={deletePhoto} selectedId={selectedId}/>
                    </div>
                    <div className="change-cover-bd-r-bottom">
                        <Pagination count={photos.length} limit={24} page={curPage} onSwitch={switchPage} />
                        <button
                            className="edit-box-btn change-cover-bd-btn edit-save"
                            onClick={() => photoSelected(selectedId, this.props.$cropper)}
                        >
                            选择
                        </button>
                        <button className=" edit-box-btn change-cover-bd-btn change-cover-bd-quit" data-am-modal-close="">取消</button>
                    </div>
                </div>
            </div>
        )
    }
}

module.exports = connect(
    state => {
        const {gallery: {photos, page, selectedId}, card} = state
        return {
            photos:photos,
            pagedPhotos: F.slice(page * 24, (page+1) * 24, photos),
            uploadServer: window.UPLOAD_URL,
            uploadToken: window.UPLOAD_TOKEN,
            curPage: page,
            selectedId,
            $cropper: state.global.$cropper
        }
    },
    (dispatch, props) => ({
        fileQueued: (file) => dispatch(fileQueued(file)),
        fileProgress: (file, percentage) => dispatch(fileProgress(file.id, percentage)),
        fileStatusChange: (file, status, uploaded) => dispatch(fileStatusChange(file.id, status, uploaded)),
        selectPhoto: (file) => {
            dispatch(selectPhoto(file.id))
        },
        cropperReady: F.compose(dispatch, cropperReady),
        photoSelected: (selectedId, $cropper = props.$cropper) => {
            if (!selectedId) {
                return alert('请选择要替换的图片!')
            }

            props.$modal.modal('close')
            $cropper.modal('open')
        },

        deletePhoto: (id) => dispatch(deletedPhote(id)),
        switchPage: F.compose(dispatch, switchPage)
    })
)(UserGallery)